package world.snowcrystal.aop;

import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RMapCache;
import org.springframework.core.annotation.Order;
import world.snowcrystal.dao.UserAuthenticationDetails;

import java.util.concurrent.TimeUnit;

@Log4j2
@Aspect
@Order(2)
//@Component
public class RedisCacheAspect {

//    @Autowired
    private RMapCache<String, UserAuthenticationDetails> mapCache;

    @Around("execution( org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String) )")
    public Object retrieveUserFromCache(ProceedingJoinPoint joinPoint) throws Throwable {
        String username = (String) joinPoint.getArgs()[0];
        UserAuthenticationDetails details = mapCache.get(username);
        if (details == null) {
            log.info("Redis Cache not hit : user {} authentication",username);
                    details = (UserAuthenticationDetails) joinPoint.proceed();
            mapCache.put(username, details,0L, TimeUnit.DAYS,0L,TimeUnit.DAYS);
        }else{
            log.info("Redis Cache hit : user {} authentication",username);
        }
        return details;
    }
}
